package com.example.proxy2_java;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MessageHandler implements InvocationHandler {
    Object msg;

    public Object bind(Object target) {
        this.msg = target;
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this
        );
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("↓ before send");
        method.invoke(this.msg, args);
        System.out.println("↑ sent");

        return null;
    }
    // public static Object newProxyInstance(ClassLoader loader,
    //                                       Class<?>[] interfaces,
    //                                       InvocationHandler h)
    //         throws IllegalArgumentException
    // {
    //     //对 Invocationhandler做判空处理
    //     Objects.requireNonNull(h);
    //     //复制[IProvider接口]
    //     final Class<?>[] intfs = interfaces.clone();
    //
    //     //根据IProvider的类加载器IProvider接口生成了Proxy类,关键：根据类加载器和接口对象在JVM缓存中生成一个类对象
    //     Class<?> cl = getProxyClass0(loader, intfs);
    //     //获取构造器
    //     final Constructor<?> cons = cl.getConstructor(constructorParams);
    //     //保存InvocationHandler的引用
    //     final InvocationHandler ih = h;
    //     //通过构造器实例化Proxy代理对象
    //     return cons.newInstance(new Object[]{h});
    // }
}
